package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thinkcool.circletextimageview.CircleTextImageView;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.ScheduleRecycleAdapter;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.utils.Eyes;

/**
 * Created by XXX on 2017/6/14.
 */

public class EvaluationByMonthActivity extends AppCompatActivity {
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private RecyclerView myRecycle;
    private EditText search_bar;
    private ScheduleRecycleAdapter adapter;
    private int year,month,userId;
    private ArrayList<Schedule> searchList;
    private ArrayList<Schedule> schedules;
    private Handler handler=new Handler();
    private String userName;
    private LinearLayout erroLinear;
    private TextView erroText;
    private Button sureSearch;
    private RelativeLayout loadingview;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.coorlayout);
        initView();
        initPhoto();
        initRecycleView();
        loadScheduleByMonth();
    }
    public void initView(){
        year=getIntent().getIntExtra("year",0);
        month=getIntent().getIntExtra("month",0);
        userId=getIntent().getIntExtra("userId",0);
        userName=getIntent().getStringExtra("userName");
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        myRecycle= (RecyclerView) findViewById(R.id.myRecycle);
        sureSearch= (Button) findViewById(R.id.sureSearch);
        erroLinear= (LinearLayout) findViewById(R.id.erroLinear);
        erroText= (TextView) findViewById(R.id.erroText);
        loadingview= (RelativeLayout) findViewById(R.id.loadingRel);
        setSupportActionBar(myToolBar);
        myToolBar.setNavigationIcon(R.mipmap.back);
        CollapsingToolbarLayout myCollap = (CollapsingToolbarLayout) findViewById(R.id.myCollap);
        myCollap.setTitle(year+"年"+month+"月");
        //  myCollap.setCollapsedTitleGravity(Gravity.CENTER);//无法居中
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        AppBarLayout barLayout = (AppBarLayout) findViewById(R.id.myAppBar);
        Eyes.setStatusBarColorForCollapsingToolbar(this, barLayout, myCollap, myToolBar, ContextCompat.getColor(this, R.color.blue));

        this.search_bar= (EditText) findViewById(R.id.taskSearch);
        setShowOrGone(1);
        search_bar.setHint("输入门店名称或时间");
        LimitsEditEnter(search_bar);
        sureSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.post(runnable);
            }
        });
        sureSearch.setEnabled(false);
        search_bar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {

                String text = search_bar.getText().toString().trim();
                if (TextUtils.isEmpty(text)){
                    sureSearch.setEnabled(false);
                    adapter = new ScheduleRecycleAdapter(schedules, EvaluationByMonthActivity.this, new ScheduleRecycleAdapter.MyCallBackClickListener() {
                        @Override
                        public void onEditorClick(Schedule schedule, int position) {
                        }
                        @Override
                        public void onLookClick(Schedule schedule, int position) {
                            Intent in=new Intent(EvaluationByMonthActivity.this,LookEvaDetialActivity.class)
                                    .putExtra("schid",schedule.getID());
                            startActivity(in);
                        }

                        @Override
                        public void onSignClick(Schedule schedule, int position) {
                        }
                        @Override
                        public void onSubmitClick(Schedule schedule, int position) {
                        }
                    });
                    myRecycle.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                }else{
                    sureSearch.setEnabled(true);
                }
            }
        });
    }

    //屏蔽回车事件
    public static void LimitsEditEnter(EditText et) {
        et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    //初始化头像
    public void initPhoto(){
        ImageView userPhoto = (ImageView) findViewById(R.id.userPhoto);
        CircleTextImageView circleText = (CircleTextImageView) findViewById(R.id.circleText);
        Employee emp= null;
        try {
            /*判断是否有头像，无则显示名字*/
            emp = db.selector(Employee.class).where("ID","=",userId).findFirst();
            if (emp==null||emp.getEmpImage()==null){
                userPhoto.setVisibility(View.GONE);
                //去掉括号
                if (userName.contains("(")&&userName.contains(")")) {
                    userName=userName.replace("(","").replace(")","");
                }
                //取最后两位
                if(userName.length()>2){
                    userName=userName.substring(userName.length()-2,userName.length());
                    circleText.setText(userName);
                }else{
                    circleText.setText(userName);
                }
            }else{
                circleText.setVisibility(View.GONE);
                //加载网络图
                String path=pubClass.pictureSavePath+emp.getEmpImage();
                Glide.with(this).load(path).error(R.mipmap.icon_error).into(userPhoto);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    public void initRecycleView(){
        LinearLayoutManager manager=new LinearLayoutManager(this);
        myRecycle.setLayoutManager(manager);
        manager.setOrientation(OrientationHelper.VERTICAL);
        //防止滑动冲突
        myRecycle.setNestedScrollingEnabled(false);
    }

    Runnable runnable =new Runnable() {
        @Override
        public void run() {
            ProgressDialog loaddialog = new ProgressDialog(EvaluationByMonthActivity.this);
            loaddialog.setMessage("正在获取数据");
            loaddialog.setCanceledOnTouchOutside(true);
            loaddialog.show();
            String data=search_bar.getText().toString().trim();
            try {
                getSdate(data);
                adapter=new ScheduleRecycleAdapter(searchList, EvaluationByMonthActivity.this, new ScheduleRecycleAdapter.MyCallBackClickListener() {
                    @Override
                    public void onEditorClick(Schedule schedule, int position) {
                    }
                    @Override
                    public void onLookClick(Schedule schedule, int position) {
                        Intent in=new Intent(EvaluationByMonthActivity.this,LookEvaDetialActivity.class)
                                .putExtra("schid",schedule.getID());
                        startActivity(in);
                    }
                    @Override
                    public void onSignClick(Schedule schedule, int position) {
                    }
                    @Override
                    public void onSubmitClick(Schedule schedule, int position) {
                    }
                });
            } catch (DbException e) {
                e.printStackTrace();
                if (loaddialog.isShowing()){
                    loaddialog.dismiss();
                }
            }
            myRecycle.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            if (loaddialog.isShowing()){
                loaddialog.dismiss();
            }
        }
    };

    //拉取搜索数据
    private void getSdate(String str) throws DbException {
        searchList=new ArrayList<>();
        if(schedules!=null){
            for (int i=0;i<schedules.size();i++){
                Shop shop=db.selector(Shop.class).where("ID","=",schedules.get(i).getShopID()).findFirst();
                String time=schedules.get(i).getSchStartTime().replaceAll("-","").replace("T"," ");
                if (shop.getShopName().contains(str)||time.contains(str)){
                    searchList.add(schedules.get(i));
                }
            }
        }else{
            BaseActivity.showAnimaDialog(this,"当前无数据查询");
            return;
        }
    }

    public void loadScheduleByMonth(){
        Map<String,String> map=new HashMap<>();
        map.put("task","loadOtherOESchedule");
        map.put("empid",userId+"");
        map.put("year",year+"");
        map.put("month",month+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    setShowOrGone(2);
                    String[] res = result.split("\\|");
                    if (res[0].equals("200")) {
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<Schedule>>() {
                        }.getType();
                        schedules = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        if (schedules != null) {
                            if (schedules.size()>=0){
                                myRecycle.setVisibility(View.VISIBLE);
                                erroLinear.setVisibility(View.GONE);
                            }else{
                                myRecycle.setVisibility(View.GONE);
                                erroLinear.setVisibility(View.VISIBLE);
                                erroText.setText("没有完成的评估哦");
                                return;
                            }

                            adapter = new ScheduleRecycleAdapter(schedules, EvaluationByMonthActivity.this, new ScheduleRecycleAdapter.MyCallBackClickListener() {
                                @Override
                                public void onEditorClick(Schedule schedule, int position) {
                                }
                                @Override
                                public void onLookClick(Schedule schedule, int position) {
                                    Intent in=new Intent(EvaluationByMonthActivity.this,LookEvaDetialActivity.class)
                                            .putExtra("schid",schedule.getID());
                                    startActivity(in);
                                }
                                @Override
                                public void onSignClick(Schedule schedule, int position) {
                                }
                                @Override
                                public void onSubmitClick(Schedule schedule, int position) {
                                }
                            });
                            myRecycle.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        }
                    } else if (res[0].equals("202")) {
                        setShowOrGone(3);
                        erroText.setText("当前无评估数据");
                    } else {
                        setShowOrGone(3);
                        erroText.setText("数据请求失败");
                    }
                }
                @Override
                public void onFailture() {
                    setShowOrGone(3);
                    erroText.setText("数据请求失败");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if (!TextUtils.isEmpty(search_bar.getText().toString().trim())){
                search_bar.setText("");
                return false;
            }else{
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    public void setShowOrGone(int k){
        if (k==1){
            loadingview.setVisibility(View.VISIBLE);
            myRecycle.setVisibility(View.GONE);
            erroLinear.setVisibility(View.GONE);
        }
        if (k==2){
            loadingview.setVisibility(View.GONE);
            myRecycle.setVisibility(View.VISIBLE);
        }
        if (k==3){//获取失败
            loadingview.setVisibility(View.GONE);
            myRecycle.setVisibility(View.GONE);
            erroLinear.setVisibility(View.VISIBLE);
            erroText.setText("数据获取失败");
        }
    }


//    //接受网络状态的判断广播
//    NetWorkStateReceiver netWorkStateReceiver;
//    int whetherConnectNetWork=0;
//    @Override
//    protected void onResume() {
//        if (netWorkStateReceiver==null){
//            netWorkStateReceiver=new NetWorkStateReceiver();
//        }
//        IntentFilter filter=new IntentFilter();
//        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        registerReceiver(netWorkStateReceiver,filter);
//        System.out.print("广播注册");
//        super.onResume();
//    }
//
//    @Override
//    protected void onPause() {
//        unregisterReceiver(netWorkStateReceiver);
//        System.out.print("广播注销");
//        super.onPause();
//    }
//
//    //用于离线状态下的voice的点击
//    class NetWorkStateReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
//                    .getSystemService(Context.CONNECTIVITY_SERVICE);
//            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
//            whetherConnectNetWork=(mNetworkInfo==null)?0:1;
//            if(whetherConnectNetWork==1){
//                loadScheduleByMonth();
//            }else{
//                //判断recycle是否有数据
//                if (schedules!=null&&schedules.size()!=0){
//                    myRecycle.setVisibility(View.VISIBLE);
//                    erroLinear.setVisibility(View.GONE);
//                }else{
//                    myRecycle.setVisibility(View.GONE);
//                    erroLinear.setVisibility(View.VISIBLE);
//                    erroText.setText("没有网络连接哦！");
//                }
//            }
//        }
//    }

}
